import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateRoleMenuDto } from './dto/create-role-menu.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { RoleMenu } from './entities/role-menu.entity';
import { Repository } from 'typeorm';

@Injectable()
export class RoleMenuService {
  constructor(
    @InjectRepository(RoleMenu)
    private readonly roleMenuRepostiory: Repository<RoleMenu>
  ) {}
  // 新增角色菜单
  async create(createRoleMenuDto: CreateRoleMenuDto) {
    try {
      return await this.roleMenuRepostiory.insert(createRoleMenuDto)
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  // 根据角色id查询角色菜单列表
  async findRoleInMenUIds(role_id: number) {
    try {
      const result = this.roleMenuRepostiory.find({
        select: {  menu_id: true },
        where: { role_id: role_id }
      })
    return result
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  // 更新角色菜单
  async update(role_id: number, menu_ids: any[]) {
    try {
      const find = await this.roleMenuRepostiory.find({
        where: { role_id }
      })
      if (find.length == 0) {
        return await this.insters(role_id, menu_ids)
      }
      if (find.length === menu_ids.length) {
        const isEvery = find.every((item) => menu_ids.includes(item.menu_id))
        if (!isEvery) {
          await this.remove(role_id)
          await this.insters(role_id, menu_ids)
        }
      } else {
        await this.remove(role_id)
        await this.insters(role_id, menu_ids)
      }
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  // 删除并重新添加
  async insters(role_id: number, menu_ids: any[]) {
    try {
        menu_ids.forEach(async (menu_id: number) => {
          await this.create({ role_id, menu_id })
        })
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  // 根据角色id删除角色菜单
  async remove(role_id: number) {
    try {
      return await this.roleMenuRepostiory.delete({role_id})
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
}
